package com.ruoyi.lipin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.lipin.domain.bo.LpTagBo;
import com.ruoyi.lipin.domain.vo.LpTagVo;
import com.ruoyi.lipin.domain.LpTag;
import com.ruoyi.lipin.mapper.LpTagMapper;
import com.ruoyi.lipin.service.ILpTagService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 标签Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-08
 */
@RequiredArgsConstructor
@Service
public class LpTagServiceImpl implements ILpTagService {

    private final LpTagMapper baseMapper;

    /**
     * 查询标签
     */
    @Override
    public LpTagVo queryById(Long tagId){
        return baseMapper.selectVoById(tagId);
    }

    /**
     * 查询标签列表
     */
    @Override
    public TableDataInfo<LpTagVo> queryPageList(LpTagBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<LpTag> lqw = buildQueryWrapper(bo);
        Page<LpTagVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询标签列表
     */
    @Override
    public List<LpTagVo> queryList(LpTagBo bo) {
        LambdaQueryWrapper<LpTag> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<LpTag> buildQueryWrapper(LpTagBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<LpTag> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getType()), LpTag::getType, bo.getType());
        lqw.like(StringUtils.isNotBlank(bo.getName()), LpTag::getName, bo.getName());
        return lqw;
    }

    /**
     * 新增标签
     */
    @Override
    public Boolean insertByBo(LpTagBo bo) {
        LpTag add = BeanUtil.toBean(bo, LpTag.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setTagId(add.getTagId());
        }
        return flag;
    }

    /**
     * 修改标签
     */
    @Override
    public Boolean updateByBo(LpTagBo bo) {
        LpTag update = BeanUtil.toBean(bo, LpTag.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(LpTag entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除标签
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
